package natappvip.liujinliang.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import natappvip.liujinliang.util.PropertiesUtil;
import natappvip.liujinliang.util.VOUtil;

/**
 * @ClassName:  DownloadServlet   
 * @Despt: 文件下载服务端处理程序  
 * @Auth: Liujinliang 
 * @Date: 2018年7月29日 下午9:43:00
 */
public class DownloadServlet extends BaseControllerServlet {

	/**   
	 * @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)   
	 */ 
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		
		request.setCharacterEncoding(PropertiesUtil.getProperty("charset"));
		response.setCharacterEncoding(PropertiesUtil.getProperty("charset"));
		
		String uuid = request.getParameter("uuid");
		// 查询文件存储的元信息
		String mdata = fileMetaDataLocalService.fetch(uuid);
		// 未在mdata.txt中查到数据 || 未在数据库中查到数据
		if (mdata == null) {
			response.getWriter().write(VOUtil.error("操作失败").toString());
			response.getWriter().write("文件不存在");
			return ;
		}
		if (mdata.contains("deleted")) {
			response.getWriter().write(VOUtil.error("操作失败").toString());
			response.getWriter().write("文件已经被删除");
			return ;
		}
		
		ByteArrayOutputStream res = fileSourceService.getResource2OutputStream(uuid);
		
		response.setContentType("text/html");
		response.setStatus(HttpServletResponse.SC_OK);
		
		if (res != null) {
			response.getWriter().println(res);
		} else {
			response.getWriter().println("<h1>文件：" + uuid + "获取OutputStream失败</h1>");
		}
		
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		doGet(request, response);
	}
}
